/*
 * @Author: hx 2542123711@QQ.com
 * @Date: 2024-12-23 15:23:32
 * @LastEditors: hx 2542123711@QQ.com
 * @LastEditTime: 2024-12-25 15:41:13
 * @FilePath: /class_socket/udp_socket/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<cstdio>
#include <memory>
#include"UdpServer.hpp"
#include<vector>

using namespace std;

//以字符串的形式输出
string Handler(const string& s)
{
    string info;
    info = "server get message: " + s;
    cout << info << endl;

    return info;
}

bool SafeCheck(const string& cmd)
{
    //先用一个容器把常见禁止的命令存储起来
    vector<string> key_word = {
        "rm",
        "cp",
        "mv",
        "kill",
        "sudo",
        "unlink",
        "yum"
    };

    //在vector的所有命令中对cmd命令进行查找比对，找到就返回false，否则true
    for(const auto& word : key_word)
    {
        auto it = cmd.find(word);
        if(it != string::npos)
        {
            return false;
        }
    }

    return true;
}

//以命令的形式输出
string ExcuteCommand(const string& cmd)
{
    if(!SafeCheck(cmd))
    {
        return "Bad cmd";
    }

    FILE* pf = popen(cmd.c_str(), "r");
    if(pf == nullptr)
    {
        perror("open fial\n");
        exit(1) ;
    }

    string result;
    char buffer[SIZE];
    while(true)
    {
        char* ok = fgets(buffer, sizeof(buffer), pf);
        if(ok == nullptr)
        {
            break;
        }

        result += buffer;
    }
    pclose(pf);

    return result;
}

int main()
{
    //用智能指针
    unique_ptr<UdpServer> up(new (UdpServer));
    up->init();

    up->run(Handler);

    return 0;
}
